#include <iostream>
#include <QtCore/QTextStream>
#include <QtWebKit/QWebFrame>
#include <QtGui/QToolTip>
#include "WebBrowser.h"
#include "MainWindow.h"
#include "Translate.h"
#include "Log.h"

WebBrowser::WebBrowser(MainWindow* mainWindow, QWidget* parent) 
	: QWebView(parent), m_mainWindow(mainWindow), m_tid(0)
{
  m_trBrowser = new WebBrowser;

  page()->settings()->setAttribute(QWebSettings::AutoLoadImages, false);
//	page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
	m_trBrowser->page()->settings()->setAttribute(QWebSettings::AutoLoadImages, false);

	connect(m_trBrowser, SIGNAL(loadFinished(bool)), this, SLOT(slot_trBrowserLoaded(bool)));
	connect(m_trBrowser, SIGNAL(loadProgress(int)), this, SIGNAL(loadProgress(int)));
//	connect(page(), SIGNAL(linkHovered ( const QString &, const QString &, const QString &)),
//	        this, SLOT(slot_linkHovered ( const QString &, const QString &, const QString &)));
  Log::m_log.setCodec("UTF-8");
}


WebBrowser::~WebBrowser(void)
{
  Log::m_log << "browser url=" << url().toString() << " deleted" << endl;
  delete m_trBrowser;
}

QWebView* WebBrowser::createWindow(QWebPage::WebWindowType)
{
	return m_mainWindow ? m_mainWindow->addBrowser(false) : NULL;
}

void WebBrowser::loadAndTranslate(const QUrl &url)
{
  Log::m_log << "Load and auto translate: " << url.toString() << endl;
//  this->load(url);
  m_trBrowser->load(url);
}

void WebBrowser::slot_trBrowserLoaded(bool)
{
  const QWebFrame* frame = m_trBrowser->page()->mainFrame();
  Log::m_log << "Auto translating " << m_trBrowser->title() << "\n"
    << "  at " << m_trBrowser->url().toString() << "\n";
  Translator *t = new Translator(m_trBrowser, frame->toHtml(), m_trBrowser->url()/*frame->baseUrl()*/, this); // after this, browser->m_tid = t->m_id
  connect(t, SIGNAL(finished()), this, SLOT(slot_translateFinished()));
  t->start();
}

void WebBrowser::slot_translateFinished()
{
  Translator* t = static_cast<Translator*>(sender());
  Log::m_log << "Auto translation done: id = " << t->m_id << " m_trBrowser->m_tid = " << m_trBrowser->m_tid
    << " url = " << t->m_url.toString() << "\n";
  if (t->m_id == m_trBrowser->m_tid) {                    // check for correct id
    this->setHtml(t->m_trHtml, t->m_url);
    m_trBrowser->m_tid = 0;
  }
  t->deleteLater();
}

void WebBrowser::slot_linkHovered( const QString & link, const QString & title, const QString & textContent )
{
  QString tr = Translator::translateText(textContent);
  if (!link.isEmpty()) {
    QUrl url = QUrl::fromUserInput(link);
    Log::m_log << "link hover (" << url.host() << ") : " << tr << endl;
//    QPoint rsize(100, 100);
    QToolTip::showText(QCursor::pos(),"(" + url.host() + ") "+tr/*,this,QRect(this->cursor().pos()-rsize, this->cursor().pos()+rsize)*/);

  }
  else
    QToolTip::hideText();
}
